<template>
  <div class="clock-in-page">
    <!-- 返回按钮 -->
    <div class="back-button">
      <router-link to="/main/renshi/kaoqing" class="back-link">返回</router-link>
    </div>

    <!-- 规则按钮 -->
    <div class="rules-button" @click="showRules = true">
      <i class="el-icon-document"></i>
      考勤规则
    </div>

    <!-- 主要内容 -->
    <div class="main-container">
      <!-- 标题 -->
      <div class="title-box">
        <h2 class="title-text">考勤打卡</h2>
        <div class="current-time">当前时间 {{ currentTime }}</div>
      </div>

      <!-- 打卡按钮容器 -->
      <div class="clock-in-container">
        <button 
          v-for="time in filteredClockTimes" 
          :key="time"
          class="clock-in-button"
          :class="{ 'clocked-in': isTimeClocked(time) }"
          @click="handleClockIn(time)"
        >
          {{ time }}
          <div class="button-status">{{ isTimeClocked(time) ? '已打卡' : '打卡' }}</div>
        </button>
      </div>
    </div>

    <!-- 音频启用提示弹窗 -->
    <div v-if="showAudioModal" class="modal-overlay">
      <div class="modal-content">
        <h3>音频提醒设置</h3>
        <p>是否启用打卡提醒音效？</p>
        <div class="modal-buttons">
          <button @click="enableAudio" class="modal-button confirm-button">确认</button>
          <button @click="disableAudio" class="modal-button cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 考勤规则对话框 -->
    <el-dialog
      title="考勤规则"
      :visible.sync="showRules"
      :show-header="false"
      width="50%"
      class="rules-dialog"
    >
      <div class="rules-content">
        <h3>上下班打卡时间</h3>
        <ul>
          <li>上午上班：8:30 - 9:00</li>
          <li>午休打卡：11:35 - 13:30</li>
          <li>下午下班：18:00 - 18:30</li>
          <li>加班打卡：19:00 - 20:30</li>
        </ul>

        <h3>考勤规定</h3>
        <ul>
          <li>每天必须完成规定时间的打卡，否则按缺勤处理</li>
          <li>迟到15分钟以上需要提交说明</li>
          <li>请假需要提前申请</li>
          <li>特殊情况需要提前请假</li>
        </ul>

        <h3>其他说明</h3>
        <p>如遇系统问题或特殊情况，请及时联系人事部门处理。</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ClockInPage',
  data() {
    return {
      clockTimes: ['8:30', '12:00', '13:30', '18:00', '19:00', '20:30'],
      currentTime: '',
      clockedTimes: ['8:30'], // 存储已打卡的时间
      timer: null,
      audio: null, // 音频对象
      reminderPlayed: {}, // 记录每个时间点是否已播放提醒
      audioEnabled: false, // 音频启用状态标志
      showAudioModal: false, // 控制音频设置弹窗的显示
      showRules: false // 控制考勤规则对话框的显示
    }
  },
  computed: {
    filteredClockTimes() {
      const now = new Date()
      const currentHours = now.getHours()
      const currentMinutes = now.getMinutes()
      
      return this.clockTimes.filter(time => {
        // 如果已经打卡，显示该按钮
        if (this.isTimeClocked(time)) return true
        
        const [hours, minutes] = time.split(':').map(Number)
        const timeInMinutes = hours * 60 + minutes
        const currentTimeInMinutes = currentHours * 60 + currentMinutes
        
        // 计算时间差（考虑跨天情况）
        let timeDiff = timeInMinutes - currentTimeInMinutes
        if (timeDiff < -15) timeDiff += 24 * 60 // 如果是第二天的时间
        
        // 只显示15分钟内的未打卡按钮
        return timeDiff >= -15 && timeDiff <= 15
      })
    }
  },
  methods: {
    // 初始化音频相关设置
    initializeAudio() {
      this.audio = new Audio('/clockin.mp3')
      this.showAudioModal = true
    },

    // 启用音频
    enableAudio() {
      this.audioEnabled = true
      this.showAudioModal = false
      // 测试音频
      this.audio.currentTime = 0
    //   this.audio.play().catch(error => {
    //     console.log('音频播放失败:', error)
    //   })
    },

    // 禁用音频
    disableAudio() {
      this.audioEnabled = false
      this.showAudioModal = false
    },
    updateCurrentTime() {
      const now = new Date()
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      this.currentTime = `${hours}:${minutes}:${seconds}`
      
      // 检查是否需要播放提醒音效
      this.checkTimeAndPlayReminder()
    },
    checkTimeAndPlayReminder() {
      if (!this.audioEnabled) return; // 如果音频未启用，直接返回

      const now = new Date()
      const currentHours = now.getHours()
      const currentMinutes = now.getMinutes()
      const currentTimeInMinutes = currentHours * 60 + currentMinutes

      this.clockTimes.forEach(time => {
        if (this.isTimeClocked(time)) return // 如果已打卡，跳过

        const [hours, minutes] = time.split(':').map(Number)
        const timeInMinutes = hours * 60 + minutes
        
        // 计算时间差（考虑跨天情况）
        let timeDiff = timeInMinutes - currentTimeInMinutes
        if (timeDiff < -15) timeDiff += 24 * 60 // 如果是第二天的时间

        // 在打卡时间前5分钟播放提醒
        if (timeDiff <= 5 && timeDiff >= 0 && !this.reminderPlayed[time]) {
          this.audio.currentTime = 0
          this.audio.play().catch(error => {
            console.log('音频播放失败:', error)
          })
          this.reminderPlayed[time] = true // 标记该时间点已播放提醒
          console.log(`播放${time}打卡提醒`)
        }
      })
    },
    handleClockIn(time) {
      if (!this.isTimeClocked(time)) {
        this.clockedTimes.push(time)
        // 播放打卡音效
        // if (this.audioEnabled) {
        //   this.audio.currentTime = 0 // 重置播放位置
        //   this.audio.play().catch(error => {
        //     console.log('音频播放失败:', error)
        //   })
        // }
        // 这里可以添加其他打卡逻辑，比如发送到服务器等
        console.log(`打卡时间: ${time}`)
      }
    },
    isTimeClocked(time) {
      return this.clockedTimes.includes(time)
    }
  },
  created() {
    this.updateCurrentTime()
    this.timer = setInterval(this.updateCurrentTime, 1000)
    this.initializeAudio()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "宋体";
}

/* 规则按钮样式 */
.rules-button {
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.rules-button:hover {
  background-color: #45a049;
}

/* 规则对话框样式 */
.rules-dialog .rules-content {
    /* font-size: 16px;
    font-weight: 600; */
  font-style: inherit;
}

.rules-content h3 {
  color: #333;
  margin: 20px 0 10px;
  font-size: 20px;
  font-weight: 600;
}

.rules-content ul {
  list-style-type: none;
  margin-bottom: 20px;
}

.rules-content li {
  margin: 10px 0;
  color: #666;
  font-size: 16px;
  line-height: 1.5;
  position: relative;
  padding-left: 20px;
}

.rules-content li:before {
  content: "•";
  position: absolute;
  left: 0;
  color: #4CAF50;
}

.rules-content p {
  color: #666;
  line-height: 1.6;
  font-size: 16px;
}

/* 页面容器 */
.clock-in-page {
  min-height: 100vh;
  background-color: #faebd7;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

/* 返回按钮 */
.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
}

.back-link {
  color: #333;
  text-decoration: none;
  font-size: 18px;
}

/* 主要内容容器 */
.main-container {
  background-color: white;
  border-radius: 15px;
  padding: 30px;
  width: 90%;
  max-width: 800px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 标题样式 */
.title-box {
  text-align: center;
  margin-bottom: 30px;
}

.title-text {
  font-size: 24px;
  color: #333;
}

/* 打卡按钮容器 */
.clock-in-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  padding: 20px;
}

/* 打卡按钮样式 */
.clock-in-button {
  background-color: #fff;
  border: 2px solid #4CAF50;
  border-radius: 8px;
  padding: 12px 20px;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 15px;
  width: 200px;
  height: 70px;
  justify-content: center;
}
.clock-in-button:hover {
  background-color: #4CAF50;
  color: white;
}

.button-status {
  font-size: 16px;
  color: #666;
}

.clock-in-button:hover .button-status {
  color: white;
}
.current-time{
    margin: 20px;
}
/* 模态弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
  width: 90%;
}

.modal-content h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 20px;
}

.modal-content p {
  margin-bottom: 20px;
  color: #666;
  font-size: 16px;
}

.modal-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.modal-button {
  padding: 10px 25px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.confirm-button {
  background-color: #4CAF50;
  color: white;
}

.confirm-button:hover {
  background-color: #45a049;
}

.cancel-button {
  background-color: #f44336;
  color: white;
}

.cancel-button:hover {
  background-color: #da190b;
}
</style>